package com.example.qxfw.cshx.controller;

import com.dmgis.service.DmServiceConnector;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.zy.BaseProduct;
import com.example.qxfw.common.entity.zy.CshxSetting;
import com.example.qxfw.common.entity.zy.CshxZsyb;
import com.example.qxfw.common.util.DocxUtil;
import com.example.qxfw.cshx.service.CshxSettingService;
import com.example.qxfw.cshx.service.FireWarningService;
import com.example.qxfw.mongodb.hy.entity.HyDocFile;
import com.example.qxfw.mongodb.hy.service.DocFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;

@Api(tags = "城市火险--火险预警")
@RestController
@CrossOrigin
@RequestMapping("/FireWarningController")
public class FireWarningController {
    @Value("${filePath.active}")
    private String active;

    @Value("${dmgis.serName}")
    private String serverName;

    @Value("${dmgis.port}")
    private String port1;

    @Autowired
    private FireWarningService fireWarningService;


    @Autowired
    private CshxSettingService cshxSettingService;

    @Autowired
    private DocFileService docFileService;

    @ApiOperation("获取显示设置")
    @GetMapping("/getSetting")
    public SysResult getSetting(){
        List<CshxSetting> list = cshxSettingService.getList();
        return SysResult.success(list);
    }

    @ApiOperation("保存显示设置")
    @PostMapping("/saveSetting")
    public SysResult saveSetting(@RequestBody CshxSetting cshxSetting){
        Integer rows = cshxSettingService.save(cshxSetting);
        return SysResult.success(rows);
    }

    @ApiOperation("更新显示设置")
    @PostMapping("/updateSetting")
    public SysResult updateSetting(@RequestBody CshxSetting cshxSetting){
        Integer rows = cshxSettingService.update(cshxSetting);
        return SysResult.success(rows);
    }

    @ApiOperation("删除显示设置")
    @GetMapping("/deleteSetting")
    public SysResult deleteSetting(String id){
        Integer rows = cshxSettingService.delete(id);
        return SysResult.success(rows);
    }

    @ApiIgnore
    @ApiOperation("城市火险--火险预警-火险预报")
    @GetMapping("/fireDangerForecasting")
    public SysResult fireDangerForecasting(String time,String timeChar) {
        List<CshxZsyb> list = fireWarningService.fireDangerForecasting(time,timeChar);
        return SysResult.success(list);
    }

    @ApiOperation("获取产品模板")
    @GetMapping("/getTemplate")
    public Object getTemplate() {
        //模板路径
        String templatePath;

        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        if (active.equals("dev")) {
            templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                    "\\src\\main\\resources\\templates\\cshxTemp\\城市火险等级预报模板.docx";
        } else {
            templatePath = applicationHome.getSource().getParentFile() +
                    "\\resource\\templates\\cshxTemp\\城市火险等级预报模板.docx";
        }
        // 设置前端响应
        byte[] buffer = new byte[1024];
        int bytesRead;
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                FileInputStream inputStream = new FileInputStream(templatePath);
        ) {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", "森林火险预警文档模板.docx");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("模板下载失败");
        }
        return null;
    }


    @ApiOperation("城市火险--火险预警-生成文档")
    @PostMapping("/forecastRelease")
    public Object forecastRelease(String date,String userName, MultipartFile[] images) throws ParseException {
        return fireWarningService.forecastRelease(date, userName, images);
    }


    @ApiOperation("城市火险--火险预警-文档查看")
    @GetMapping("/viewDocx")
    public void viewDocx(String time, HttpServletResponse response) throws IOException {
        String strType = "城市火险等级预报产品";
        String productName = new StringBuilder().append(time).append(strType).append(".doc").toString();
        int id = fireWarningService.selectByNameOfProduct(productName);
        HyDocFile hyDocFile = docFileService.getByTableId(String.valueOf(id));
        if (hyDocFile != null) {
            InputStream inputStream = new ByteArrayInputStream(hyDocFile.getData());
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("doc_File", "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
        } else {
            System.out.println("文件不存在");
        }
    }

    @Value("${dmgis.image_url}")
    private String imageUrl;

    @ApiIgnore
    @ApiOperation("城市火险--火险预警-火险易发区")
    @RequestMapping(value = "fireProneAreas")
    public String fireProneAreas(String forecastDate) {
        String s = fireWarningService.fireProneAreas(forecastDate);
        DmServiceConnector conn = new DmServiceConnector(serverName, port1);
        String callPlugin = conn.getCallPlugin("contourservice", "GetContourPic", s + "|yl|500|500|109.53914234,21.6297788700001,110.893801633,23.127373617|1");
        //String callPlugin = conn.getCallPlugin("contourservice", "GetContourPic", "230209113059|yy|500|500|12324873.109580431,3246274.863703763,12572940.077137733,3442956.5166840963|1");
        return imageUrl + callPlugin;
    }

}
